<template>
  <div class="login-container">
    <div class="ms-login">
      <img src="../assets/img/logo.png" alt="" class="logo">
      <div class="ms-title">{{title}}</div>
      <el-form :model="ruleForm" :rules="rule" ref="ruleForm" label-width="0px" class="demo-ruleForm">
        <el-form-item prop="username">
            <el-input v-model="ruleForm.username" placeholder="userName" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item prop="password">
            <el-input type="password" placeholder="passWord"  auto-complete="off" v-model="ruleForm.password" @keyup.enter.native="submitForm('ruleForm')" show-password></el-input>
        </el-form-item>
        <div class="login-btn">
            <el-button type="primary" @click="submitForm('ruleForm')" :loading="logining">{{$t('login.login')}}</el-button>
        </div>
      </el-form>
    </div>
    <div class="langSelect">
      <el-select size="small" v-model="langStyle" placeholder="请选择语言">
        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>
    </div>
    <el-dialog :visible.sync="partVisible" width="30%" justify="space-around" :before-close="handleClose">
      <el-row :gutter="40">
        <el-col :span=12 v-for="(item, index) in partnerList" :key="index"><div @click="selectPartner(item.id)" class="partnerBox">{{item.partnerName}}</div></el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import fn from 'src/utils/fn.js';
export default {
  data: function () {
    return {
      ruleForm: {
        username: '',
        password: ''
      },
      ruleForm1: {},
      // rules: '',
      logining: false,
      sessionid: '',
      langStyle: '',// 当前选择的语言
      title: '',
      partnerList:[],
      partVisible:false,
      partnerId:'',
      rule:{
        username: [{ required: true, message: this.$t('login.required'), trigger: 'blur' }],
        password: [{ required: true, message: this.$t('login.required'), trigger: 'blur' }]
      }
    }
  },
  computed: {
    options () {
      let arr = [{value: '1', label: '中文'},{value: '2', label: 'indonesia'},{value: '3', label: 'Tiếng việt nam'}]//{value: '4', label: 'English'}
      // if (this.$store.state.common.lang === 'id') {
      //   arr.push({value: '2', label: 'indonesia'})
      // } else if (this.$store.state.common.lang === 'vi') {
      //   arr.push({value: '3', label: 'Tiếng việt nam'})
      // } else if (this.$store.state.common.lang === 'PHL') {
      //   arr.push({value: '4', label: 'English'})
      // }
      return arr
    }
  },
  methods: {
    selectPartner(id){
      this.partnerId=id;
      this.submitForm('ruleForm');
    },
    handleClose(done) {
        this.partnerId="";
        done();
    },
    submitForm (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.logining = true;
          // eslint-disable-next-line
          let jse = new JSEncrypt();
          jse.setPublicKey(this.$store.state.common.publicKey);
          //   设置需要加密的字符串
          let encrypted = jse.encrypt(this.ruleForm.password);
          let option = {
            param:{
              partnerId:this.partnerId,
              userName: this.ruleForm.username,
              password: encrypted
            }
          }
          let accToken;
          // this.$axios.defaults.headers.common['Accept-Language'] = 'zh-CN';
          this.$axios.post(this.$action.login,option).then(tokendata => {
            this.logining = false;
            if(tokendata.code==200){
              if(tokendata.data.token){
                accToken=tokendata.data.token.accessToken;
                // sessionStorage.setItem('Token', accToken);
                // sessionStorage.setItem('refreshToken', tokendata.data.token.refreshToken);
              }else if(tokendata.data.partnerList){
                this.partnerList=tokendata.data.partnerList;
                this.partVisible=true;
              }
              if(accToken){
                // let loginIn= this.$action.loginIn+'?access_token='+accToken;
                let loginIn= this.$action.loginIn;

                this.$axios.post(loginIn,{param:{}}).then(res => {
                  if(res.code==200){
                    this.ruleForm.password = '';
                    let menulist=fn.treeDataTranslate(res.data.menuList,'id','parentId');
                    console.log(menulist);
                    menulist=menulist[0].children;
                    let btnRole={};
                    let menuEach = (data) => {
                      data.forEach(el => {
                        let arr=[];
                        if(el.children && el.children[0].type==2){
                          el.children.forEach(ch =>{
                            arr.push(ch.route);
                          })
                          btnRole[el.route]=arr;
                        }else if (el.children && el.children[0].type==1) {
                          menuEach(el.children);
                        }else if(!el.children && el.type==1){
                          btnRole[el.route]=arr;
                        }
                      });
                      return btnRole;
                  };
                  btnRole = menuEach(menulist);
                  console.log(btnRole);
                    sessionStorage.setItem('topMenu', menulist[0].route);
                    sessionStorage.setItem('sessionid', res.data.id);
                    sessionStorage.setItem('nickName', res.data.nickName);
                    sessionStorage.setItem('name', res.data.userName);
                    sessionStorage.setItem('menulist', JSON.stringify(menulist));
                    sessionStorage.setItem('rolelist', JSON.stringify(btnRole));
                    this.$store.commit('setPermiss',JSON.stringify(btnRole));
                    this.$router.push('/emptypage');
                  }   
                })
              }
            }else{
              this.$globalMsg.error(tokendata.message);
            }
          })
        } else {
          return false;
        }
      })
    },
    lang () { //设置默认本地语言
      let browserLanguage =(navigator.language || navigator.browserLanguage).toLowerCase();
      console.log(browserLanguage);
      if(browserLanguage=='zh'){
        this.langStyle='1';
      }else if(browserLanguage=='id'){
        this.langStyle='2';
      }else if(browserLanguage=='vi'){
        this.langStyle='3';
      }else if(browserLanguage=='phl'){
        this.langStyle='4';
      }
      // if(browserLanguage=='cn'){
      //   this.langStyle='1';
      //   this.$i18n.locale = 'cn';
      //   sessionStorage.setItem("lang","cn");
      //   sessionStorage.setItem("first_unit","");
      //   sessionStorage.setItem("last_unit","");
      //   this.$axios.defaults.headers.common['Accept-Language'] = 'zh-CN';
      // }else if(browserLanguage=='id'){
      //   this.langStyle='2';
      //   this.$i18n.locale = 'id';
      //   sessionStorage.setItem("lang","id");
      //   sessionStorage.setItem("first_unit","RP");
      //   sessionStorage.setItem("last_unit","");
      //   this.$axios.defaults.headers.common['Accept-Language'] = 'in-ID';
      // }else if(browserLanguage=='vi'){
      //   this.langStyle='3';
      //   this.$i18n.locale = 'vi';
      //   sessionStorage.setItem("lang","vi");
      //   sessionStorage.setItem("first_unit","");
      //   sessionStorage.setItem("last_unit","VND");
      //   this.$axios.defaults.headers.common['Accept-Language'] = 'vi-VN';
      // }else if(browserLanguage=='phl'){
      //   this.langStyle='4';
      //   this.$i18n.locale = 'phl';
      //   sessionStorage.setItem("lang","phl");
      //   sessionStorage.setItem("first_unit","");
      //   sessionStorage.setItem("last_unit","PHP");
      //   this.$axios.defaults.headers.common['Accept-Language'] = 'en-PH';
      // }
      // if (this.langStyle == 1) {
      //   this.$i18n.locale = 'cn';
      //   sessionStorage.setItem("lang","cn");
      //   sessionStorage.setItem("first_unit","");
      //   sessionStorage.setItem("last_unit","");
      //   this.$axios.defaults.headers.common['Accept-Language'] = 'zh-CN';
      // }
    }
  },
  watch: {
    langStyle () {
      let lang,first_unit,last_unit;
      console.log('langStyle');
      if (this.langStyle === '1') {       
        this.$i18n.locale = 'cn';
        lang='cn';
        first_unit='';
        last_unit='';
        this.$axios.defaults.headers.common['Accept-Language'] = 'zh-CN';
      }
      if (this.langStyle === '2') {
        this.$i18n.locale = 'id';
        lang='id';
        first_unit='';
        last_unit='Rp';
        this.$axios.defaults.headers.common['Accept-Language'] = 'in-ID';
      }
      if (this.langStyle === '3') {
        this.$i18n.locale = 'vi';
        lang='vi';
        first_unit='';
        last_unit='VND';
        this.$axios.defaults.headers.common['Accept-Language'] = 'vi-VN';
      }
      if (this.langStyle === '4') {
        this.$i18n.locale = 'phl';
        lang='phl';
        first_unit='';
        last_unit='PHP';
        this.$axios.defaults.headers.common['Accept-Language'] = 'en-PH';
      }
      sessionStorage.setItem('lang', lang);
      sessionStorage.setItem('first_unit', first_unit);
      sessionStorage.setItem('last_unit', last_unit);
      this.$store.commit('setLang',{lang,first_unit,last_unit});
    }
  },
  mounted () {
    sessionStorage.clear();
    this.lang();
    this.title = global.config.headerTotal;
    // if(JsSrc.indexOf('zh')>=0)
    // {
    // }
    // else if(JsSrc.indexOf('en')>=0)
    // {
    // }
    // else
    // {}
  }
}

</script>

<style scoped>
.login-container {
  height: 100vh;
  background-color: #141a48;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}
.login-wrap {
  position: relative;
  width: 100%;
  height: 100%;
  
}
.noclick{
  display: none;
}
.ms-title {
  width: 100%;
  margin: 0 auto;
  margin-bottom: 40px;
  text-align: center;
  font-size: 16px;
  color:#fff;
  /* color: #0B8FCF; */
}
.logo{
  display: block;
  width: 42px;
  height: 49px;
  margin:0 auto 20px;
}
.ms-login {
  min-width: 400px;
  height: auto;
  padding:10px 40px;
  border-radius: 5px;
}
.login-btn {
  text-align: center;
}
.login-btn button {
  width: 100%;
  height: 36px;
}

.langSelect{
  position: absolute;
  width: 300px;
  padding: 5px;
  right: 10%;
  top: 5%;
}

.partnerBox{
  background-color:#409EFF;
  text-align: center;
  line-height: 50px;
  margin:15px;
  cursor: pointer;
  color:#fff;
  font-size: 16px;
}
</style>
